<script setup>
import { ref, onMounted, watch } from 'vue'
import { getInfoBySkuApi } from '@/api/warehousingentry/warehousingEntryDetails'
// import { getInfoBySkuApi as warehousingEntryUp } from '@/api/warehousingentry/warehousingEntryUp'
import axios from 'axios'

// 接收外部传入的商品列表
const props = defineProps({
  goodsList: {
    type: Array,
    default: () => []
  }
})

// 弹窗状态
const dialogVisible = ref(false)

// 仓库信息
const warehouseInfo = ref([])
const warehouseList = ref()

//获取仓库库存信息
// 在 WarehouseDial.vue 中确保返回的数据包含所有必要字段
const fetchWarehouseStock = async (skuId) => {
  try {
    const res = await getInfoBySkuApi(skuId)
    const dataList = res.data || res.rows || res || []
    
    return dataList.map(item => ({
      id: item.id,
      skuId: item.skuId,
      batchNumber: item.batchNumber || '',
      availableQuantity: item.count || 0,
      supplierId: item.supplierId || 0,
      price: item.price || 0,
      warehousingEntryId: item.warehousingEntryId || 0,
      realArrivalTime: item.realArrivalTime || '',
      predictedArrivalTime: item.predictedArrivalTime || '',
      status: item.status || 1,
      quantity: 0,
      warehouseId: item.warehouseId || 0,  // 确保包含 warehouseId
      areaId: item.areaId || 0,            // 确保包含 areaId
      locationId: item.locationId || 0     // 确保包含 locationId
    }))
  } catch (error) {
    console.error('获取仓库库存失败:', error)
    return []
  }
}

// 当前选中的商品
const selectedGoods = ref(null)
const handleGoodsSelectionChange = (val) => {
  if (val.length > 0) {
    selectedGoods.value = val[0]
    fetchWarehouseStock(val[0].id).then(data => {
      warehouseInfo.value = data
    })
  } else {
    warehouseInfo.value = []
  }
}
const selectedWarehouses = ref(null)
const handleWarehouseSelectionChange = (val) => {
  selectedWarehouses.value = val[0]
}
// 提交
const emit = defineEmits(['submit'])
const submit = () => {
  const result = {
    goods: selectedGoods.value,
    warehouseStock: selectedWarehouses.value
    // warehouseStock: warehouseInfo.value.filter(w => w.quantity > 0)
  }
  // const warehouseId = selectedWarehouses.value?.id || 0
   warehouseList.value = selectedWarehouses.value
  emit('submit', result)
  dialogVisible.value = false
}

// 关闭
const cancel = () => {
  dialogVisible.value = false
}

// 打开弹窗
const open = () => {
  dialogVisible.value = true
}

// 监听goodsList变化，确保数据同步
watch(() => props.goodsList, (newVal) => {
  // 可以在这里处理数据变化逻辑
})

defineExpose({
  warehouseList,
  open
})
</script>

<template>
  <el-dialog v-model="dialogVisible" title="商品与仓库信息" width="1300px" top="5vh">
    <div style="display: flex; height: 600px; overflow: hidden;">
      <!-- 左侧：商品列表 -->
      <div style="flex: 1; border-right: 1px solid #ebeef5; overflow: hidden;">
        <div style="height: 100%; overflow-y: auto;">
          <el-table :data="goodsList" @selection-change="handleGoodsSelectionChange" style="width: 100%">
            <el-table-column type="selection" width="55" fixed />
            <el-table-column prop="name" label="商品名称" min-width="150" />
            <el-table-column prop="code" label="商品编码" min-width="150" />
            <el-table-column prop="specCode" label="规格编码" min-width="150" />
            <el-table-column prop="totalQuantity" label="总数量" width="100" />
          </el-table>
        </div>
      </div>

      <!-- 右侧：仓库信息 -->
      <div style="flex: 2; padding: 10px; overflow: hidden;">
        <div style="height: 100%; overflow-x: auto; overflow-y: auto;">
          <el-table :data="warehouseInfo" style="width: 100%; min-width: 800px;"
            @selection-change="handleWarehouseSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="id" label="库存ID" width="80" />
            <el-table-column prop="skuId" label="商品ID" width="80" />
            <el-table-column prop="availableQuantity" label="可用数量" width="100" />
            <el-table-column prop="batchNumber" label="批号" min-width="120" />
            <el-table-column prop="price" label="价格" width="100" />
            <el-table-column prop="supplierId" label="供应商ID" width="100" />
            <el-table-column prop="warehousingEntryId" label="入库单ID" width="120" />
            <el-table-column prop="realArrivalTime" label="实际到货时间" min-width="180" />
            <el-table-column prop="predictedArrivalTime" label="预计到货时间" min-width="180" />
            <el-table-column prop="status" label="状态" width="80" />
            <el-table-column label="分配数量" width="120" fixed="right">
              <template #default="{ row }">
                <el-input-number v-model="row.quantity" :min="0" :max="row.availableQuantity" size="small"
                  style="width: 100px;" />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">关闭</el-button>
        <el-button type="primary" @click="submit">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>